#include "dialog.h"
#include "ui_dialog.h"
#include <QBuffer>
#include <QDebug>
#include <QSharedMemory>

QSharedMemory sharedMemory;

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    sharedMemory.setKey("QSharedMemoryExample");
    connect(ui->btnRead,SIGNAL(clicked()),this,SLOT(loadFromFile()));
}

void Dialog::loadFromMemory()
{
    // 将共享内存与该进程绑定
    if (!sharedMemory.attach())
    {
        qDebug() << "Unable to attach to shared memory segment.";
        return;
    }

    // 从共享内存中读取数据
    QBuffer buffer;
    QDataStream in(&buffer);
    QImage image;

    sharedMemory.lock();
    buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
    buffer.open(QBuffer::ReadOnly);
    in >> image;
    sharedMemory.unlock();

    sharedMemory.detach();
    ui->label->setPixmap(QPixmap::fromImage(image));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_btnRead_clicked()
{
    loadFromMemory();
}
